package gitobject;
import repository.Repository;
import zlib.ZLibUtils;

import java.io.*;


public class GitObject {

    protected String fmt;                  //type of object
    protected String key;                  //key of object
    protected String mode;                 //mode of object
    protected static String path = Repository.getGitDir() + File.separator + "objects";          //absolute path of objects
    protected String value;                //value of object

    public String getFmt(){
        return fmt;
    }
    public String getKey() { return key; }
    public String getMode(){
        return mode;
    }
    public String getPath() {
        return path;
    }
    public String getValue(){
        return value;
    }


    public GitObject(){}
    /**
     * Get the value(content) of file
     * @param file
     * @return String
     * @throws IOException
     */
    public static String getValue(File file) throws IOException {
        /* Todo: Add your code here
         *   You should delete the return statement below before coding.  */
        FileInputStream is = new FileInputStream(file);
        int count = 0;
        while(count == 0){ //不使用int count = is.available()是为了防止在进行网络操作时出错
            count = is.available();//在读写操作前得知数据流中有多少个字节可以读取
        }
        byte[] bytes = new byte[count];
        is.read(bytes);//按照字节数组的方式进行读取
        String str = new String(bytes);//字节数组转化为字符串
        is.close();
        return str;
    }
    /**
     * Todo: Serialize the object to the local repository.
     * @throws Exception
     */
    public void writeObject() throws Exception{
        /**
         * Add your code here.
         */
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path + File.separator + key));
        oos.writeObject(value);//按字符串写入
        oos.close();
    }

    /**
     * Todo: Serialize the object and compress with zlib.
     * @throws Exception
     */
    public void compressWrite() throws Exception{
        /**
         * Add your code here.
         */
        byte[] bytes = ZLibUtils.compress(value.getBytes());//将value转化为字节数组并对其进行压缩
        FileOutputStream fos = new FileOutputStream(path + File.separator + key);
        fos.write(bytes);
        fos.close();
    }

}